﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using StockHelper.Scripts;
using StockHelper.Scripts.Comm;
using StockHelper.Scripts.Sound;

namespace StockHelper
{
    public partial class VoiceForm : Form
    {
        bool onlyStock = false;
        private Image voiceType;
        private Image voiceType_click;
        private Image voicesList_item;
        private Image voicesList_item_click;

        private Panel lastClickTypeBtn;
        private Style.ExLabel lastClickVoiceBtn;

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;//用双缓冲绘制窗口的所有子控件
                return cp;
            }
        }

        public VoiceForm(bool e = false)
        {
            onlyStock = e;
            InitializeComponent();

            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景. 
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }
        
        public Hashtable data;


        private void VoiceForm_Load(object sender, EventArgs e)
        {
            this.BackgroundImage = Assets.LoadImg(Config.Get("bgImage", UI.bgImage));
            voiceType = Assets.LoadImg(UI.voiceType);
            voicesList_item = Assets.LoadImg(UI.voicesList_item);
            this.VoicesList.BackgroundImage = Assets.LoadImg(UI.voicesList);
            this.AddVoiceBtn.BackgroundImage = this.AddVoiceBtn.Image = Assets.LoadImg(UI.main_新增股票_btn);
            
            bool show = true;
            foreach (Assets.Package package in Assets.packages)
            {
                CreateListBtn(package, show);
                show = false;
            }
            ScrollBar_Init();
            this.AddVoiceBtn.Enabled = false;
        }


        private void CreateVoiceList(Assets.Package package = null, Panel click = null)
        {
            if (package == null)
                package = Assets.packages[0];
            if (lastClickTypeBtn != null)
                lastClickTypeBtn.BackgroundImage = voiceType;
            if(click != null)
                click.BackgroundImage = voiceType_click;
            lastClickTypeBtn = click;
            lastClickTypeBtn.BackgroundImage = voiceType_click;

            Hashtable table = new Hashtable { };
            table["price"] = new ArrayList();

            foreach (string key in package.price.Keys)
            {
                Hashtable data = package.price[key] as Hashtable;
                (table["price"] as ArrayList).Add(new Hashtable {
                    { "name" ,  data["name"].ToString() },
                    { "jsonPath" , package.jsonPath },
                    { "key" , data["key"].ToString() },
                    { "isPrice" , 1 },
                });
            }
            if (!onlyStock)
            {
                foreach (string key in package.keys.Keys)
                {
                    Hashtable data = package.keys[key] as Hashtable;
                    string type = data["type"].ToString();
                    if (type != "price")
                    {
                        if (!table.ContainsKey(type)) table[type] = new ArrayList();
                        (table[type] as ArrayList).Add(new Hashtable {
                        { "name" , data["name"].ToString() },
                        { "jsonPath" , package.jsonPath },
                        { "sound" , package.voicePath + data["sound"].ToString() },
                    });
                    }
                }
            }
            this.InfoPanel.Controls.Clear();
            Hashtable translate = package.data.ContainsKey("translate") ? package.data["translate"] as Hashtable : new Hashtable();
            foreach (string key in table.Keys)
            {
                Panel panel = new Panel {
                    Anchor = AnchorStyles.Left | AnchorStyles.Right,
                    AutoSize = true,
                    AutoSizeMode = AutoSizeMode.GrowOnly,
                    BackColor = Color.Transparent,
                    Margin = new Padding(10, 10, 10, 20),
                    BackgroundImage = voicesList_item,
                    BackgroundImageLayout = ImageLayout.Stretch,
                    Width = this.InfoPanel.Width - 20,
                };
                panel.Controls.Add(new Style.ExLabel
                {
                    Text = translate.ContainsKey(key) ? translate[key].ToString() : key,
                    BackColor = Color.Transparent,
                    Font = new Font("微软雅黑", 15),
                    Margin = new Padding(10, 10, 10, 20),
                    AutoSize = true,
                    ForeColor = Color.White,
                    Padding = new Padding(10,10,0,0),
                    //Width = this.InfoPanel.Width,
                });
                FlowLayoutPanel items = new FlowLayoutPanel
                {
                    AutoSize = true,
                    Location = new Point(0, 35),
                    BackColor = Color.Transparent,
                    AutoSizeMode = AutoSizeMode.GrowOnly,
                    //AutoSizeMode = AutoSizeMode.GrowAndShrink,
                    Margin = new Padding(20,0,20,0),
                    Height = 1,
                    Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right,
                    Padding = new Padding(0,10,0,0),
                    Width = panel.Width,
                };
                panel.Controls.Add(items);
                foreach (Hashtable v in table[key] as ArrayList)
                {
                    Style.ExLabel item = new Style.ExLabel
                    {
                        Text = v["name"].ToString(),
                        TextAlign = ContentAlignment.MiddleCenter,
                        BackColor = Color.Transparent,
                        Margin = new Padding(10, 5, 10, 5),
                        Font = new Font("微软雅黑", 11),
                        AutoSize = true,
                        ImageAlign = ContentAlignment.MiddleCenter,
                        ForeColor = Color.White,
                        Cursor = Cursors.Hand,
                    };

                    item.MouseClick += new MouseEventHandler((sender, e) =>
                    {
                        if (lastClickVoiceBtn != null)
                            lastClickVoiceBtn.BackColor = Color.Transparent;
                        lastClickVoiceBtn = item;
                        lastClickVoiceBtn.BackColor = Color.Silver;
                        Item_Click(v, sender);
                    });
                    item.DoubleClick += new EventHandler((sender, e) =>
                    {
                        data = v;
                        AddVoiceBtn_Click(sender, e);
                    });
                    items.Controls.Add(item);
                }
                this.InfoPanel.Controls.Add(panel);
            }
        }


        private void CreateListBtn(Assets.Package package, bool show = false)
        {
            Panel panel = new Panel
            {
                Width = 100,
                Height = 50,
                BackgroundImage = voicesList_item,
                BackgroundImageLayout =  ImageLayout.Zoom,
            };
            Style.ExLabel label = new Style.ExLabel
            {
                Text = package.name,
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = Color.Transparent,
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 13),
            };
            panel.Controls.Add(label);
            label.MouseClick += new MouseEventHandler((sender, e) =>
            {
                CreateVoiceList(package, panel);
            });
            
            this.VoicesList.Controls.Add(panel);
            if (show)
            {
                CreateVoiceList(package, panel);
            }
        }
        

        public void Item_Click(Hashtable hashtable, object sender)
        {
            this.AddVoiceBtn.Enabled = true;
            data = hashtable;
        }
        private void AddVoiceBtn_Click(object sender, EventArgs e)
        {
            if (data.ContainsKey("isPrice") && data["isPrice"].ToString() == "1")
            {
                new AddStockVoice(this, data).Show();
            }
            else
            {

                Config.Get("voicePlay", new ArrayList()).Add(data);
                Config.Save();
                VoicePlay.e.Init();
                this.Close();
                this.Dispose();
            }
        }

        private void XunFei_Click(object sender, EventArgs e)
        {
            MessageBox.Show("功能开发中");
        }


        private void ScrollBar_Init()
        {
            if (this.InfoPanel.Height <= this.InfoPanelBox.Height)
            {
                this.ScrollBar.Visible = false;
                return;
            }
            this.ScrollBar.Visible = true;
            //滑块高度=可视高度/实际高度*滚动条高度（pn_scroll.Height）
            float length = (float)this.InfoPanelBox.Height / (float)this.InfoPanel.Height * (float)this.ScrollBar.Height;
            this.ScrollBar.SliderHeight = (int)length;

            this.ScrollBar.MouseDown += ScrollBar_MouseDown;
            this.ScrollBar.MouseUp += ScrollBar_MouseUp;
            this.ScrollBar.ValueChanged += ScrollBar_ValueChanged;  //滚动条拖动事件
            this.ScrollBar.GotFocus += ScrollBar_GotFocus;  //滚动条获得焦点事件
            this.InfoPanel.MouseWheel += ScrollBar_MouseWheel; //pn_info添加滚轮事件
        }
        bool isMouseWheel = false; //防止滚轮带动的滚动条再次触发sb_ValueChanged
        //pn_info滚轮事件
        private void ScrollBar_MouseWheel(object sender, MouseEventArgs e)
        {
            isMouseWheel = true;
            int scrollRang = 40; //每次滚动高度(px)
            int sbRang = calSbRang(scrollRang); //滚动条实际滚动幅度
            if (e.Delta > 0) //滚轮向上
            {
                if (this.ScrollBar.Value - sbRang <= 0)
                {
                    //滚动到顶，直接设为默认值，防止滚动产生的误差
                    this.ScrollBar.Value = 0;
                    this.InfoPanel.Top = 0;
                }
                else
                {
                    this.ScrollBar.Value -= sbRang;
                    this.InfoPanel.Top += scrollRang;
                }
            }
            else//滚轮向下
            {
                if (this.ScrollBar.Value + sbRang >= 100)
                {
                    //滚动到底，直接设为默认值，防止滚动产生的误差
                    this.ScrollBar.Value = 100;
                    this.InfoPanel.Top = -(this.InfoPanel.Height - this.InfoPanelBox.Height);
                }
                else
                {
                    this.ScrollBar.Value += sbRang;
                    this.InfoPanel.Top -= scrollRang;
                }
            }
        }
        //因为滚动条滚动幅度可能是小数，转int后会损失精度，导致滚动到底或到底时产生一定误差
        float residue = 0; //float转int后舍去的小数部分累积凑1
        private int calSbRang(int scrollRang)
        {
            float temp = ((float)scrollRang) / (float)(this.InfoPanel.Height - this.InfoPanelBox.Height) * 100;//滚动条滚动比例
            int sbRang = Convert.ToInt32(temp);//保留整数部分
            residue += temp - (float)sbRang; //累积舍去的小数部分
            if (residue >= 1)
            {
                residue -= 1;
                sbRang += 1;
            }
            return sbRang;
        }

        //滚动条获取焦点时把焦点给pn_info,防止触发滚动条的滚轮事件(滚动条的滚轮滑动和容器内的滑动速度不一致)
        private void ScrollBar_GotFocus(object sender, EventArgs e)
        {
            isMouseWheel = false;
            this.InfoPanel.Focus();
        }

        //滚动条拖动
        private void ScrollBar_ValueChanged(object sender, EventArgs e)
        {
            if (!isMouseWheel)
            this.InfoPanel.Top = -Convert.ToInt32((float)this.ScrollBar.Value / 100 * (float)(this.InfoPanel.Height - this.InfoPanelBox.Height));
        }

        private void ScrollBar_MouseDown(object sender, MouseEventArgs e) {
            this.InfoPanelBox.BackColor = Color.Silver;
        }
        private void ScrollBar_MouseUp(object sender, MouseEventArgs e) {
            this.InfoPanelBox.BackColor = Color.Transparent;
        }


    }
}